package cn.ac.iie.di.wx.handler;


import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import cn.ac.iie.di.wx.common.RuntimeEnv;
import cn.ac.iie.di.wx.httpservice.HttpSender;
import cn.ac.iie.di.wx.utils.GenerateMD5Util;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Administrator
 */
public class WxPictureUrl_cache_yizhuang implements HandlerI {
    
    static Logger logger = Logger.getLogger(WxPictureUrl_cache_yizhuang.class.getName());
    
    @Override
    public void init() throws Exception {
    }
    
    @Override
    public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            
            String _idurlStr = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
            logger.info(_idurlStr);
            byte[] bytesContent = new byte[1024 * 2];
            int bytesReadIn = 0;
            ServletOutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            JSONObject urljSON = JSONObject.parseObject(_idurlStr);
            String url = urljSON.getString("url");
            String download_url_MD5 = GenerateMD5Util.string2MD5(url) + ".jpg";
            File file = new File((String) RuntimeEnv.getParam(RuntimeEnv.PICCACHE) + download_url_MD5);
            logger.info((String) RuntimeEnv.getParam(RuntimeEnv.PICCACHE) + download_url_MD5);
            if (file.exists() && ((String) RuntimeEnv.getParam(RuntimeEnv.cacheFlag)).equals("true")) {
                try {

                    //龙存已经存在该图片，读取文件进行返回
                    logger.info("read from file");
                    InputStream responseIn = new FileInputStream(file);
                    if (responseIn.available() == 0) {
                        
                        logger.info("this file is empty," + "removing is " + file.delete());
                        responseIn = new ByteArrayInputStream(("腾讯图片接口调用失败：" + "图片大小为零").getBytes("UTF-8"));
                    }
                    BufferedInputStream bis = new BufferedInputStream(responseIn);
                    while ((bytesReadIn = bis.read(bytesContent, 0, 1024 * 2)) > 0) {
                        bos.write(bytesContent, 0, bytesReadIn);
                    }
                    bos.flush();
                    bos.close();
                    bis.close();
                } catch (IOException e) {
                    logger.error("加载本地图片出错" + e.getMessage(), e);
                }
            } else {
                //龙存没有该图片，进行下载，并将图片写入 龙存
                try {
                    
                    logger.info("downlad from server");
                    file.createNewFile();
                    FileOutputStream outputStream = new FileOutputStream(file);
                    BufferedOutputStream fileOut = new BufferedOutputStream(outputStream);
//                InputStream responseIn = org.apache.http.client.fluent.Request.Get(download_url.replace("10.177.138.34", "10.238.3.12"))
//                        .execute().returnContent().asStream();
                    //从数北下载
                    HttpSender hs = new HttpSender();
                    logger.info("request is "+_idurlStr+"====to http post = "+(String) RuntimeEnv.getParam(RuntimeEnv.wxPicQueryUrl));
                    InputStream responseIn = hs.picInputStream(_idurlStr, (String) RuntimeEnv.getParam(RuntimeEnv.wxPicQueryUrl));
                    if (responseIn.available() == 0) {
                        //下载图片出错的情况
                        logger.info("腾讯图片接口调用失败：" + "下载图片大小为零");
                        InputStream inputStream = new ByteArrayInputStream(("腾讯图片接口调用失败：" + "下载图片大小为零").getBytes("UTF-8"));
                        while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                            bos.write(bytesContent, 0, bytesReadIn);
                        }
                    } else {
                        while ((bytesReadIn = responseIn.read(bytesContent, 0, 1024 * 2)) > 0) {
                            bos.write(bytesContent, 0, bytesReadIn);
                            fileOut.write(bytesContent, 0, bytesReadIn);
                        }
                    }
                    fileOut.flush();
                    bos.flush();
                    fileOut.close();
                    outputStream.close();
                    bos.close();
                } catch (IOException e) {
                    logger.error("下载图片出错" + e.getMessage(), e);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
    
}
